// utils/loginUtils.js
// 基础配置

import getBaseUrl from './baseUrl'
// const baseConfig = 'https://xit-edu.cn/2502boleapi/bole';
const baseConfig =getBaseUrl
export const login = (username, password, callback) => {
    uni.showLoading({ title: '登录中...', mask: true });
    uni.request({
        url: `${baseConfig}/sweep/login`, // 若依的登录接口地址
        data: {
            username: username,
            password: password
        },
        method: 'POST',
        header: { 'content-type': 'application/json' },
        success: (res) => {
			
            const { token:token, code: responseCode,user:userInfo } = res.data;
            if (responseCode === 200) {
				saveToken(token,userInfo)
			 uni.switchTab({
			            url: '/pages/device/device' // 确保这个路径是正确的 tabBar 页面路径
			        });
                if (callback) {
                    callback();
                }
            } else {
				console.log(res)
                uni.showToast({ title:res.data.msg, icon: 'error' });
            }
        },
        fail: (res) => {
			console.log(res)
            uni.showToast({ title: '登录服务器失败！', icon: 'error' });
        },
        complete: () => {
            uni.hideLoading();
        }
    });
};
import { eventBus } from './eventBus';
// 保存 token 的函数示例
const saveToken = (token,userInfo) => {
	// 触发全局登录成功事件（携带新 token）
	  eventBus.emit('login-success', { 
	    token: token 
	  })
	// uni.setStorageSync('userId',userInfo.userId)
	// console.log(uni.getSto)
	// uni.setStorageSync('userInfo',userInfo)
    uni.setStorageSync('token', token);
	
};

// 获取 token
export const getToken = () => {
  const authInfo = uni.getStorageSync('userInfo');
  const token = uni.getStorageSync('token');
  if (authInfo && token) {
	  // console.log(token)
    return 'Bearer ' + token;
  }
  return null;
};

// 删除用户相关信息
export const removeUserInfo = (callback) => {
  uni.showLoading({ title: '退出中...' });
  uni.removeStorage({
    key: 'wxInfo',
    success: () => {
      uni.removeStorage({
        key: 'authInfo',
        success: (res) => {
          callback && callback(res);
          uni.showToast({ title: '退出成功！', icon: 'success' });
        },
        complete: () => {
          uni.hideLoading();
        }
      });
    }
  });
};
// utils/device.js
export function getSafePlatform() {
  const systemInfo = uni.getSystemInfoSync() || {}
  return (systemInfo.platform || '').toLowerCase()
}